import { defineStore } from 'pinia'
import request from '@/utils/request'
import type { ApiResponse } from '@/types/api'

// 案件类型
interface Lawcase {
  id: number
  case_code: string
  case_cause?: string
  case_cause_id?: number
  court_name: string
  main_lawyer_name: string
  secondary_lawyer_name: string
  client_info: string
  opponent_info: string
  status: string
  type: number
  stage: number
  session_court_name: string
  session_time: string
  entrust_date: string
  create_time: string | number
  update_time: string | number
  // 其他可能的字段
  [key: string]: any
}

// 当事人类型
interface Party {
  id: number
  case_id: number
  party_id: number
  name: string
  mobile: string
  relationship: number
  is_client: number
  create_time: string
  update_time: string
}

// 案件律师类型
interface CaseLawyer {
  id: number
  case_id: number
  lawyer_id: number
  is_main: number
  create_time: string
  update_time: string
  lawyer_name: string
}

// 案件进度类型
interface CaseProgress {
  id: number
  case_id: number
  event_type: number
  event_time: string
  content: string
  operator_name: string
  create_time: number
}

// 法院类型
interface Court {
  id: number
  name: string
  province: string
  city: string
  dist: string
  address: string
  phone: string
  create_time: string
  update_time: string
}

// 案件文档类型
interface CaseDoc {
  id: number
  case_id: number
  title: string
  doc_type: number
  doc_type_text: string
  file_path: string
  file_name: string
  file_size: number
  uploader: string
  create_time: string
  update_time: string
  file_ids?: string
  file_array?: any[]
}

// 状态类型
interface LawcaseState {
  cases: Lawcase[]
  caseTotal: number
  parties: Party[]
  partyTotal: number
  caseLawyers: CaseLawyer[]
  caseLawyerTotal: number
  caseProgresses: CaseProgress[]
  caseProgressTotal: number
  courts: Court[]
  courtTotal: number
  caseDocs: CaseDoc[]
  caseDocTotal: number
  docTypes: any[]
  // 缓存文档详情，key为文档ID，value为Promise避免重复请求
  caseDocDetailCache: Map<number, Promise<ApiResponse<CaseDoc>>>
}

// 案件管理相关API
const lawcaseApi = {
  // 获取案件列表
  getCaseList: (params: any): Promise<ApiResponse<{ list: Lawcase[]; total: number }>> => {
    return request({
      url: '/api/lawcase/cases/list',
      method: 'get',
      params,
    })
  },

  // 获取当事人列表
  getPartyList: (params: any): Promise<ApiResponse<{ list: Party[]; total: number }>> => {
    return request({
      url: '/api/lawcase/parties/list',
      method: 'get',
      params,
    })
  },

  // 获取案件关联律师列表
  getCaseLawyerList: (params: any): Promise<ApiResponse<CaseLawyer[]>> => {
    return request({
      url: '/api/lawcase/cases/get_lawyers',
      method: 'get',
      params,
    })
  },

  // 获取所有在职律师列表
  getAllLawyers: (params: any): Promise<ApiResponse<CaseLawyer[]>> => {
    return request({
      url: '/api/lawcase/cases/get_all_lawyers',
      method: 'get',
      params,
    })
  },

  // 获取案件进度列表
  getProgressList: (params: any): Promise<ApiResponse<CaseProgress[]>> => {
    return request({
      url: '/api/lawcase/progresses/list',
      method: 'get',
      params,
    })
  },

  // 获取法院列表
  getCourtList: (params: any): Promise<ApiResponse<Court[]>> => {
    return request({
      url: '/api/lawcase/courts/list',
      method: 'get',
      params,
    })
  },

  // 获取启用的法院列表（用于下拉选择）
  getEnabledCourtList: (): Promise<ApiResponse<Court[]>> => {
    return request({
      url: '/api/lawcase/courts/set',
      method: 'get',
    })
  },

  // 获取案件文档列表
  getCaseDocList: (params: any): Promise<ApiResponse<CaseDoc[]>> => {
    return request({
      url: '/api/lawcase/casedocs/list',
      method: 'get',
      params,
    })
  },

  // 获取文档类型列表
  getDocTypeList: (): Promise<ApiResponse<any[]>> => {
    return request({
      url: '/api/lawcase/get_doctype_list',
      method: 'get',
    })
  },

  // 获取案由列表
  getCaseCauseList: (params: any): Promise<ApiResponse<any[]>> => {
    return request({
      url: '/api/lawcase/casecauses/list',
      method: 'get',
      params,
    })
  },

  // 获取案由选择列表
  getCaseCauseSelectList: (): Promise<ApiResponse<any[]>> => {
    return request({
      url: '/api/lawcase/casecauses/select_list',
      method: 'get',
    })
  },

  // 搜索案由（用于远程搜索）
  searchCaseCauses: (keyword: string): Promise<ApiResponse<any[]>> => {
    return request({
      url: '/api/lawcase/casecauses/search',
      method: 'get',
      params: { keyword },
    })
  },

  // 查看单个案件信息
  viewCase: (id: number): Promise<ApiResponse<Lawcase>> => {
    return request({
      url: `/api/lawcase/cases/view?id=${id}`,
      method: 'get',
    })
  },

  // 删除案件（软删除）
  deleteCase: (id: number): Promise<ApiResponse<null>> => {
    return request({
      url: '/api/lawcase/cases/del',
      method: 'delete',
      data: { id },
    })
  },

  // 解除当事人关联
  unlinkParty: (params: { id: number }): Promise<ApiResponse<null>> => {
    return request({
      url: '/api/lawcase/parties/unlink',
      method: 'post',
      data: params,
    })
  },

  // 删除案件进度（软删除）
  deleteProgress: (id: number): Promise<ApiResponse<null>> => {
    return request({
      url: '/api/lawcase/progresses/del',
      method: 'delete',
      data: { id },
    })
  },

  // 获取案件文档详情
  getCaseDocDetail: (id: number): Promise<ApiResponse<CaseDoc>> => {
    return request({
      url: '/api/lawcase/casedocs/view',
      method: 'get',
      params: { id },
    })
  },

  // 根据当事人ID获取相关案件
  getRelatedCasesByPartyId: (
    partyId: number,
    params?: any
  ): Promise<ApiResponse<{ list: Lawcase[]; total: number }>> => {
    return request({
      url: '/api/lawcase/parties/get_related_cases',
      method: 'get',
      params: { party_id: partyId, ...params },
    })
  },
}

export const useLawcaseStore = defineStore('lawcase', {
  state: (): LawcaseState => ({
    cases: [],
    caseTotal: 0,
    parties: [],
    partyTotal: 0,
    caseLawyers: [],
    caseLawyerTotal: 0,
    caseProgresses: [],
    caseProgressTotal: 0,
    courts: [],
    courtTotal: 0,
    caseDocs: [],
    caseDocTotal: 0,
    docTypes: [],
    // 初始化文档详情缓存
    caseDocDetailCache: new Map(),
  }),

  actions: {
    // 获取案件列表
    async getCaseListAction(params: any): Promise<ApiResponse<{ list: Lawcase[]; total: number }>> {
      try {
        const res = await lawcaseApi.getCaseList(params)
        if (res.code === 0) {
          // 修复：使用类型断言确保能够正确访问list和total属性
          const data = res.data as any
          this.cases = data.list || []
          this.caseTotal = data.total || 0
        }
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 获取当事人列表
    async getPartyListAction(params: any): Promise<ApiResponse<{ list: Party[]; total: number }>> {
      try {
        const res = await lawcaseApi.getPartyList(params)
        if (res.code === 0) {
          // 修复：使用类型断言确保能够正确访问list和total属性
          const data = res.data as any
          this.parties = data.list || []
          this.partyTotal = data.total || 0
        }
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 获取案件关联律师列表
    async getCaseLawyerListAction(params: any): Promise<ApiResponse<CaseLawyer[]>> {
      try {
        const res = await lawcaseApi.getCaseLawyerList(params)
        if (res.code === 0) {
          this.caseLawyers = res.data
          this.caseLawyerTotal = res.count || 0
        }
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 获取所有在职律师列表
    async getAllLawyersAction(params: any): Promise<ApiResponse<CaseLawyer[]>> {
      try {
        const res = await lawcaseApi.getAllLawyers(params)
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 获取案件进度列表
    async getProgressListAction(params: any): Promise<ApiResponse<CaseProgress[]>> {
      try {
        const res = await lawcaseApi.getProgressList(params)
        if (res.code === 0) {
          // 修复：使用类型断言确保能够正确访问list和total属性
          const data = res.data as any
          this.caseProgresses = data.list || []
          this.caseProgressTotal = data.total || 0
        }
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 获取法院列表
    async getCourtListAction(params: any): Promise<ApiResponse<Court[]>> {
      try {
        const res = await lawcaseApi.getCourtList(params)
        if (res.code === 0) {
          this.courts = res.data
          this.courtTotal = res.count || 0
        }
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 获取启用的法院列表（用于下拉选择）
    async getEnabledCourtListAction(): Promise<ApiResponse<Court[]>> {
      try {
        const res = await lawcaseApi.getEnabledCourtList()
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 获取案件文档列表
    async getCaseDocListAction(params: any): Promise<ApiResponse<CaseDoc[]>> {
      try {
        const res = await lawcaseApi.getCaseDocList(params)
        if (res.code === 0) {
          // 根据实际API返回的数据结构进行处理
          // 数据直接在res.data中，总数量在res.count中
          this.caseDocs = res.data || []
          this.caseDocTotal = res.count || 0
        }
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 获取文档类型列表
    async getDocTypeListAction(): Promise<ApiResponse<any[]>> {
      try {
        const res = await lawcaseApi.getDocTypeList()
        if (res.code === 0) {
          this.docTypes = res.data
        }
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 获取案由列表
    async getCaseCauseListAction(params?: any): Promise<ApiResponse<any[]>> {
      try {
        const res = await lawcaseApi.getCaseCauseList(params || {})
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 获取案由选择列表
    async getCaseCauseSelectListAction(): Promise<ApiResponse<any[]>> {
      try {
        const res = await lawcaseApi.getCaseCauseSelectList()
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 搜索案由（用于远程搜索）
    async searchCaseCausesAction(keyword: string): Promise<ApiResponse<any[]>> {
      try {
        const res = await lawcaseApi.searchCaseCauses(keyword)
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 查看单个案件信息
    async viewCaseAction(id: number): Promise<ApiResponse<Lawcase>> {
      try {
        const res = await lawcaseApi.viewCase(id)
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 删除案件（软删除）
    async deleteCaseAction(id: number): Promise<ApiResponse<null>> {
      try {
        const res = await lawcaseApi.deleteCase(id)
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 解除当事人关联
    async unlinkPartyAction(params: { id: number }): Promise<ApiResponse<null>> {
      try {
        const res = await lawcaseApi.unlinkParty(params)
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 删除案件进度（软删除）
    async deleteProgressAction(id: number): Promise<ApiResponse<null>> {
      try {
        const res = await lawcaseApi.deleteProgress(id)
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 获取案件文档详情（带缓存机制）
    async getCaseDocDetail(id: number): Promise<ApiResponse<CaseDoc>> {
      // 检查缓存中是否已有该文档的请求
      if (this.caseDocDetailCache.has(id)) {
        console.log(`文档${id}详情命中缓存，直接返回`)
        return this.caseDocDetailCache.get(id)!
      }

      // 创建新的请求Promise
      const requestPromise = (async () => {
        try {
          const res = await lawcaseApi.getCaseDocDetail(id)
          // 请求成功后从缓存中移除（或者保持缓存，根据需求决定）
          // 这里选择保持缓存，避免重复请求
          return res
        } catch (error) {
          // 请求失败时从缓存中移除，避免缓存失败结果
          this.caseDocDetailCache.delete(id)
          throw error
        }
      })()

      // 将Promise存入缓存
      this.caseDocDetailCache.set(id, requestPromise)

      return requestPromise
    },

    // 清除文档详情缓存（可选方法）
    clearCaseDocDetailCache(docId?: number): void {
      if (docId) {
        // 清除指定文档的缓存
        this.caseDocDetailCache.delete(docId)
      } else {
        // 清除所有缓存
        this.caseDocDetailCache.clear()
      }
    },

    // 根据当事人ID获取相关案件
    async getRelatedCasesByPartyIdAction(
      partyId: number,
      params?: any
    ): Promise<ApiResponse<{ list: Lawcase[]; total: number }>> {
      try {
        const res = await lawcaseApi.getRelatedCasesByPartyId(partyId, params)
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },
  },
})
